package com.start.platform.core;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.start.platform.core.entity.StartPlatformConfigEntity;
import com.start.platform.core.model.StartBasePlatformEntity;
import com.start.platform.core.security.StartPlatformUserInfoLoadService;
import com.start.platform.core.service.StartPlatformConfigService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Slf4j
@Configuration
@ComponentScan("com.start.platform.core.**")
@MapperScan("com.start.platform.core.mappers.**")
public class StartPlatformAutoConfiguration implements CommandLineRunner {
    @Autowired
    private StartPlatformConfigService platformConfigService;

    @Bean
    @ConditionalOnMissingBean
    public StartPlatformUserInfoLoadService startPlatformUserInfoLoadService() {
        return new StartPlatformUserInfoLoadService();
    }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     */
    @Override
    public void run(String... args) {
        log.info("开始加载第三方平台配置");
        List<StartPlatformConfigEntity> configEntityList = platformConfigService.list(new LambdaQueryWrapper<StartPlatformConfigEntity>().ge(StartBasePlatformEntity::getIsEnable, 1));
        if (configEntityList.isEmpty()) return;
        for (StartPlatformConfigEntity entity : configEntityList) {
            try {
                StartPlatformManage.getInstance().add(entity.getPlatformType(), entity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("第三方平台配置加载完毕：" + configEntityList.size());
    }
}
